Problem Set 2

1. Guessing game

  • User should be able to enter a number
  • User should be informed that entered number is either greater than or less than actual number
  • User should given 3 choices
  • User either wins i.e correctly guesses the number
  • Or loses i.e uses all the choices without correctly guessing

Condition

  • if/else conditional should be used
  • try/except conditional should be used

Hint

  • use random module to generate a random number
import random

random.randrange(10, 99)
  • use while loop to ask user for a number until satisfied
  • use break to break out of while loop
i = 0
while i < 3:
    print("I am in loop")
    if guess == number:
        break
    i += 1

Revision

# set a default user value
user_value = 1

try:
    # this is first entry point
    user_value = int(input("Enter a number"))
except ValueError:
    # if a exception is raised then code enters this block
    # exception is raised when our assumption about program goes wrong
    # as above we assume that user provides 1 2 3 which are returned as string
    # but if user provides a b c then ValueError is raised because those cannot be 
    # converted by int() function
    print("Entered value is not valid, using default value")
else:
    # if exception is not raised then we move to this block
    # any code written here can be written inside try block as in other languages 
    # but it is clean and more pythonic this way
    user_value = user_value ** 2
finally:
    # this block is always executed, ie at any condition we move to this block
    # so this block should be used as cleaning purpose, or for any task which is 
    # always run no matter what
    print("user value at this point is {}".format(user_value))

In [ ]:


In [ ]:


In [ ]: